package 链表;

/* https://leetcode-cn.com/problems/remove-linked-list-elements/ */
public class _203_移除链表元素 {

    public class ListNode {

        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode removeElements(ListNode head, int val) {

        //单独处理头节点
        while(head != null && head.val == val){
            head = head.next;
        }

        if (head == null){return null;}

        while (head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
            }else {
                head = head.next;
            }
            head.next = head.next.next;
        }
        return  head;
    }

    public ListNode removeElements2(ListNode head, int val) {

        //单独处理头节点
        while(head != null && head.val == val){
            head = head.next;
        }

        if (head == null){return null;}

        // 如果不把head和head.next的值赋给一个变量的话，程序执行就会和预期结果不相符（不知道为什么，反正下次做这种题直接定义一个变量）
        ListNode pre_node = head;
        ListNode cur_node = head.next;
        while (cur_node != null) {
            if (cur_node.val == val) {
                pre_node.next = cur_node.next;
            }else {
                pre_node = cur_node;
            }
            cur_node = cur_node.next;
        }
        return  head;


    }
}
